import 'dart:convert';
import 'dart:io';

import 'package:core_package/core_package.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app_unionad/core/configuration.dart';
import 'package:flutter_app_unionad/event_or_delegate/reload_event.dart';
import 'package:flutter_app_unionad/request/login_request.dart';
import 'package:flutter_app_unionad/ui/my_facility/my_facility_page.dart';
import 'package:flutter_app_unionad/ui/my_facility/recharge_page.dart';
import 'package:flutter_app_unionad/ui/partnership/facility_list_page.dart';
import 'package:flutter_app_unionad/ui/partnership/partnership_page.dart';
import 'package:flutter_app_unionad/ui/promotion/promotion_page.dart';
import 'package:flutter_app_unionad/ui/user_center/user_center_page.dart';
import 'package:flutter_app_unionad/ui/workbench/workbench_page.dart';
import 'package:flutter_app_unionad/view_model/change_device_event.dart';
import 'initialize_items.dart';
import 'package:jpush_flutter/jpush_flutter.dart';

class MainScreen extends StatefulWidget {
  static const String routeName = "/";

  @override
  _MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  int _index = 0;
  PageController? _pageController;

  @override
  void initState() {
    print('_MainScreenState');
    // TODO: implement initState
    super.initState();
    _pageController = PageController(
      initialPage: _index,
    );
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      initPlatformState();
    });
  }

  final JPush jpush = new JPush();

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // jpush.cleanTags();
    // jpush.setup(
    //   appKey: "cd2797ac35abdbd9f6da4e71", //你自己应用的 AppKey
    //   channel: "developer-default",
    //   production: true,
    //   debug: true,
    // );
    // jpush.applyPushAuthority(new NotificationSettingsIOS(sound: true, alert: true, badge: true));
    //
    // // Platform messages may fail, so we use a try/catch PlatformException.
    // jpush.getRegistrationID().then((rid) {
    //   print("flutter get registration id : $rid"); //1a1018970a6049da468
    //   ///记录注册id
    //   UserCacheUil.setString(Configuration.jsPushRegisterId, rid);
    //
    //   ///服务器保存  jsPush 注册id
    //   LoginRequest.saveJSPushRegister();
    //   // setState(() {
    //   //   debugLable = "flutter getRegistrationID: $rid";
    //   // });
    // });

    jpush.addEventHandler(onReceiveNotification: (Map<String, dynamic> message) async {
      jpush.cleanTags();
      // Fluttertoast.showToast(msg: "onReceiveNotification: ${message.toString()}");

      print("flutter onReceiveNotification: $message");

      // setState(() {
      //   debugLable = "flutter onReceiveNotification: $message";
      // });
    }, onOpenNotification: (Map<String, dynamic> message) async {
      /// 点击通知栏消息，在此时通常可以做一些页面跳转等
      jpush.cleanTags();
      // Fluttertoast.showToast(msg: "onOpenNotification: ${message.toString()}");
      Map? extras = message['extras'];
      print('1');

      if (extras != null) {
        print('2');
        if (Platform.isIOS) {
          print('3');

          Map? jyData = extras['jyData'];
          openParme(jyData: jyData);
        } else if (Platform.isAndroid) {
          print('4');
          print("441  --- $extras");
          print("442  --- ${extras['cn.jpush.android.EXTRA']}");

          String jyDataString = extras['cn.jpush.android.EXTRA'];
          Map jyData = jsonDecode(jyDataString);
          print('object ---$jyData');
          print(jyData['jyData']);
          openParme(jyData:jyData['jyData']);
        }
      } else {
        print('5');

        Map jyData = message['jyData'];

        openParme(jyData:jyData);
      }

      print("flutter onOpenNotification: $message");
      // setState(() {
      //   debugLable = "flutter onOpenNotification: $message";
      // });
      // NavigatorUtil.push(context, )
    }, onReceiveMessage: (Map<String, dynamic> message) async {
      jpush.cleanTags();
      // Fluttertoast.showToast(msg: "onReceiveMessage: ${message.toString()}");

      print("flutter onReceiveMessage: $message");
      // setState(() {
      //   debugLable = "flutter onReceiveMessage: $message";
      // });
    }, onReceiveNotificationAuthorization: (Map<String, dynamic> message) async {
      jpush.cleanTags();
      // Fluttertoast.showToast(msg: "onReceiveNotificationAuthorization: ${message.toString()}");

      print("flutter onReceiveNotificationAuthorization: $message");
      // setState(() {
      //   debugLable = "flutter onReceiveNotificationAuthorization: $message";
      // });
    });

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    // setState(() {
    //   debugLable = platformVersion;
    // });
  }

  void openParme({Map? jyData}) {
    print('$jyData');

    if (jyData != null) {
      print('22222222222222');

      String bizType = jyData['bizType'];

      print('bizType  ---- $bizType');

      if (bizType == '01' || bizType == '02') {
        // 01缴费提醒   02 欠费提醒
        NavigatorUtil.push(context, RechargePage.routeName);
      } else if (bizType == '03') {
        //03 推广金币到账
        if (mounted)
          setState(() {
            _index = 1;
          });
      } else if (bizType == '04') {
        //04 收益到账
        if (mounted)
          setState(() {
            _index = 2;
          });
        // NavigatorUtil.push(context, FacilityListPage.routeName);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        body: PageView(
          children: [
            MyFacilityPages(),
            PromotionPage(),
            PartnershipPage(),
            if (UserCacheUil.getInt(Configuration.userType) == 2) WorkbenchPage(),
            UserCenterPage(),
          ],
          onPageChanged: _changeIndex,
          controller: _pageController,
          physics: NeverScrollableScrollPhysics(), //禁止滑动
        ),
        bottomNavigationBar: BottomNavigationBar(
          items: [
            BuildBottomItems(
              norImage: "icon_tab1",
              selectImage: "icon_tab1_1",
              title: "我的设备",
            ),
            BuildBottomItems(
              norImage: "icon_tab2",
              selectImage: "icon_tab2_1",
              title: "推广",
            ),
            BuildBottomItems(
              norImage: "icon_tab5",
              selectImage: "icon_tab5_1",
              title: "合伙人",
            ),
            if (UserCacheUil.getInt(Configuration.userType) == 2)
              BuildBottomItems(
                norImage: "icon_tab4",
                selectImage: "icon_tab4_1",
                title: "工作台",
              ),
            BuildBottomItems(
              norImage: "icon_tab3",
              selectImage: "icon_tab3_1",
              title: "个人中心",
            ),
          ],
          selectedFontSize: MyFont.font10,
          unselectedFontSize: MyFont.font10,
          selectedItemColor: MyColors.color_34_34_34,
          unselectedItemColor: MyColors.color_102_102_102,
          onTap: _changeIndex,
          currentIndex: _index,
          type: BottomNavigationBarType.fixed,
        ),
      ),
    );
  }

  void _changeIndex(int index) async {
    setState(() {
      _pageController?.jumpToPage(index);
      _index = index;
      eventBus.fire(TabViewReloadDataEvent(index: index));
    });
  }

  int last = 0;

  Future<bool> _onWillPop() {
    int now = DateTime.now().millisecondsSinceEpoch;
    if (now - last > 8000) {
      last = DateTime.now().millisecondsSinceEpoch;
      ShowToastWidget.showToast(msg: "再次点击返回退出应用", gravity: ToastGravity.BOTTOM);
      return Future.value(false);
    } else {
      return Future.value(true);
    }
  }
}
